<template>
	<view>
		<view class="search-box">
			<uni-search-bar @input="input" :radius="100" placeholder="请输入搜索内容" cancelButton="none" />
		</view>

		<view class="result-list" @click="goToGoodsDetail">
			<view class="result-item" v-for="(item, index) in searchResult" :key="index">
				<view class="result-text" :data-goodsId="item.goods_id">{{item.goods_name}}</view>
				<uni-icons type="arrowright" size="32rpx"></uni-icons>
			</view>
		</view>

		<view class="history-list" v-if="searchResult.length === 0">
			<view class="history-title">
				<text>历史搜索</text>
				<uni-icons type="trash" size="20" @click="clean"></uni-icons>
			</view>

			<view class="history-item">
				<uni-tag @click="goToGoodsList(item)" circle="false" :text="item" v-for="(item,index) in history" :key="index"></uni-tag>
			</view>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				timer: null,
				kw: '',
				searchResult: [],
				historyList: []
			};
		},
		computed:{
			history(){
				return [...this.historyList].reverse()
			}
		},
		methods: {
			input(e) {
				clearTimeout(this.timer)

				this.timer = setTimeout(() => {
					this.kw = e.trim()
					this.getSearchInfo()
				}, 500)
			},
			async getSearchInfo() {
				if (this.kw === '') {
					this.searchResult = []
					return
				}
				const {
					data: res
				} = await uni.$http.get('/api/public/v1/goods/qsearch', {
					query: this.kw
				})
				this.searchResult = res.message
				this.saveSearchHistory()
			},
			goToGoodsDetail(e) {
				uni.navigateTo({
					url: `/subpkg/goods_detail/goods_detail?cid=${e.target.dataset.goodsid}`
				})
			},
			saveSearchHistory(){
				const set = new Set(this.historyList)
				set.delete(this.kw)
				set.add(this.kw)
				this.historyList = Array.from(set)
				uni.setStorageSync('kw', JSON.stringify(this.historyList))
			},
			clean(){
				this.historyList=[]
				uni.setStorageSync('kw','[]')
			},
			goToGoodsList(kw){
				uni.navigateTo({
					url:`/subpkg/goods_list/goods_list?query=${kw}`
				})
			}
		},
		onLoad(){
			this.historyList=JSON.parse(uni.getStorageSync('kw') || '[]')
		}
	}
</script>

<style lang="scss">
	.search-box {
		position: sticky;
		top: 0;
	}

	.result-list {
		padding: 10rpx 0;
	}

	.result-item {
		height: 80rpx;
		line-height: 80rpx;
		font-size: 26rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		padding: 0 10rpx;
		border-bottom: 1rpx solid #efefef;

		.result-text {
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			margin-right: 6rpx;
		}
	}

	.history-list {
		padding: 0 20rpx;

		.history-title {
			display: flex;
			justify-content: space-between;
			border-bottom: 1rpx solid #efefef;
			padding-bottom: 10rpx;
		}

		.history-item {
			display: flex;
			flex-wrap: wrap;

			.uni-tag {
				display: block;
				margin-top: 10rpx;
				margin-right: 10rpx;
			}
		}
	}
</style>
